﻿#region

using System.Web.Mvc;
using HouseHoldBudget.Core.Authentication;
using HouseHoldBudget.Core.Entities.User;
using HouseHoldBudget.Framework.Authentication;
using HouseHoldBudget.Framework.Mvc.Helpers;
using HouseHoldBudget.Models.Account;
using HouseHoldBudget.Services.Users;

#endregion

namespace HouseHoldBudget.Controllers
{
    public class AccountController : Controller
    {
        #region Readonly & Static Fields

        private readonly IUserService _userService;

        #endregion

        #region Constructors

        public AccountController(IUserService userService)
        {
            _userService = userService;
        }

        #endregion

        #region Instance Methods

        /// <summary>
        ///   Logs the off.
        /// </summary>
        /// <returns> </returns>
        public ActionResult LogOff()
        {
            BudgetFormsAuthenticationService.SignOut();

            return View();
        }

        /// <summary>
        ///   Logs the on.
        /// </summary>
        /// <returns> </returns>
        public ActionResult LogOn()
        {
            return View();
        }

        /// <summary>
        ///   Logs the on.
        /// </summary>
        /// <param name="model"> The model. </param>
        /// <param name="returnUrl"> The return URL. </param>
        /// <returns> </returns>
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                BudgetUser result = _userService.ValidateUser(model.UserName, model.Password);
                if (result != null)
                {
                    BudgetFormsAuthenticationService.SetAuthentication(new BudgetIdentity(result));

                    return RedirectToAction("Index", "Home");
                }
                return RedirectToAction(Url.Home());
            }

            return View(model);
        }

        public ActionResult UnauthorizedAccess()
        {
            return View();
        }

        #endregion
    }
}